import { Layers, Node, SpriteFrame, UITransform } from 'cc'

export const createUINode = (name: string = '') => {
  const node = new Node(name)
  const transform = node.addComponent(UITransform)
  // 设置锚点为左上角
  transform.setAnchorPoint(0, 1)
  node.layer = 1 << Layers.nameToLayer('UI_2D')
  return node
}

export const randomByRange = (start: number, end: number) => {
  return Math.floor(start + (end - start) * Math.random())
}

// 根据名称序号从小到大排序
export const sortSpriteFrame = (spriteFrames: SpriteFrame[]) => {
  const reg = /\((\d+)\)/  // idle(9) => 9
  return spriteFrames.sort((a, b) => {
    const aIndex = a.name.match(reg)[1]
    const bIndex = b.name.match(reg)[1]
    return Number(aIndex) - Number(bIndex)
  })
}

// 生成随机长度字符串
export const randomByLen = (len: number) => {
  return Array.from({length:len}).reduce<string>((prev,curr) => {
    return prev + Math.floor(Math.random()* 10)
  },'')
}

// 深拷贝
export const deepClone = <T>(obj: T, hash = new WeakMap()): T => {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  // 处理循环引用
  if (hash.has(obj)) {
    return hash.get(obj)
  }

  // 处理日期对象
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any
  }

  // 处理正则表达式
  if (obj instanceof RegExp) {
    return new RegExp(obj.source, obj.flags) as any
  }

  // 处理 Map
  if (obj instanceof Map) {
    const map = new Map()
    hash.set(obj, map)
    obj.forEach((value, key) => {
      map.set(deepCopy(key, hash), deepCopy(value, hash))
    })
    return map as any
  }

  // 处理 Set
  if (obj instanceof Set) {
    const set = new Set()
    hash.set(obj, set)
    obj.forEach(value => {
      set.add(deepCopy(value, hash))
    })
    return set as any
  }

  // 处理数组和普通对象
  const result = Array.isArray(obj) ? [] : {}
  hash.set(obj, result)

  Object.keys(obj).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      ;(result as any)[key] = deepCopy((obj as any)[key], hash)
    }
  })

  return result as T
}
